package com.ayuan.blog.interceptor;

import com.alibaba.fastjson.JSON;
import com.ayuan.blog.bean.CommonResponseBean;
import com.ayuan.blog.common.util.CookieUtils;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by xiaozhu on 16/8/11.
 */
@Log4j2
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info(request.getRequestURI());
        Cookie cookie = CookieUtils.getCookie(request, "sessionId");
        if (cookie == null) {
            log.info("cookie is null");
            response.getWriter().write(JSON.toJSONString(new CommonResponseBean<Object>(10, "login out of time", null)));
            return false;
        } else {
//            String userName = (String) request.getSession().getAttribute("sessionId" + cookie.getValue());
            String userName = stringRedisTemplate.opsForValue().get("sessionId" + cookie.getValue());
            if (StringUtils.isNotEmpty(userName)) {
                System.out.println(userName + " login");
            } else {
                log.info("session out of time");
                response.getWriter().write(JSON.toJSONString(new CommonResponseBean<Object>(10, "login out of time", null)));
                return false;
            }
        }
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
